package com.banciyuan.bcywebview.utils.encrypt;

import java.math.BigInteger;
import java.nio.charset.Charset;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.UUID;

/**
 * Created by zzjin on 5/14/14.
 */
public class MD5 {

	private static final String HASH_ALGORITHM = "MD5";
	private static final int RADIX = 10 + 26; // 10 digits + 26 letters

	public static String getMD5Name(String imageUri) {
		byte[] md5 = getMD5(imageUri.getBytes(Charset.defaultCharset()));
		BigInteger bi = new BigInteger(md5).abs();
		return bi.toString(RADIX);
	}

	private static byte[] getMD5(byte[] data) {
		byte[] hash = null;
		try {
			MessageDigest digest = MessageDigest.getInstance(HASH_ALGORITHM);
			digest.update(data);
			hash = digest.digest();
		} catch (NoSuchAlgorithmException e) {
		}
		return hash;
	}

	public static String getMD5(String content) {
		try {
			MessageDigest digest = MessageDigest.getInstance("MD5");

			if(null!=content){
				digest.update(content.getBytes(Charset.defaultCharset()));
			}else{
				digest.update("".getBytes(Charset.defaultCharset()));
			}
			return getHashString(digest);
		} catch (Exception e) {
		}
		return "";
	}

	private static String getHashString(MessageDigest digest) {
		StringBuilder builder = new StringBuilder();
		for (byte b : digest.digest()) {
			builder.append(Integer.toHexString((b >> 4) & 0xf));
			builder.append(Integer.toHexString(b & 0xf));
		}
		return builder.toString();
	}

	public static String getUUID() {
		String s = UUID.randomUUID().toString().replace("-", "");
		return s;
	}
}
